package com.tungse.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author Tungse
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 收到的数据（自动转为 ByteBuf）
        ByteBuf buf = (ByteBuf) msg;
        String received = buf.toString(CharsetUtil.UTF_8);
        System.out.println("收到客户端消息: " + received);

        // 回写相同数据
        ByteBuf response = Unpooled.copiedBuffer("Server: " + received, CharsetUtil.UTF_8);
        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}